<?php
if(isset($_GET['token'])){
    $token = $_GET['token'];
    header("Content-Type: text/event-stream");
    header("Cache-Control: no-cache");
    header("Connection: keep-alive");
    header('X-Accel-Buffering: no');
    set_time_limit(0); //防止超时
    ob_end_clean(); //清空（擦除）缓冲区并关闭输出缓冲
    ob_implicit_flush(1); //这个函数强制每当有输出的时候，即刻把输出发送到浏览器。这样就不需要每次输出（echo）后，都用flush()来发送到浏览器了

    echo "retry:1000\n";
    echo "event:message\n";
    $key = "SSE_".$token;
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    //$redis->auth();
    while(true){
        $msg = $redis->lPop($key);
        if(!empty($msg)){
            echo "data: ".$msg."\n\n";        
        }
        else{
            //echo "data: {}\n\n"; 
            sleep(1); 
        }        
    }
}
